package com.cheer.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.cheer.enums.CaptchaEnum;
import com.cheer.exception.ServiceException;
import com.cheer.security.SecurityConfig;
import com.cheer.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author cheer
 */
@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    private static final int CAPTCHA_WIDTH = 200;
    private static final int CAPTCHA_HEIGHT = 100;
    private static final int CAPTCHA_COUNT = 4;
    private static final int CAPTCHA_LINE = 150;
    private static final String SECURITY_ACCOUNT_ID = "securityAccountId";

    @Override
    public void getCaptcha(Integer width, Integer height, Integer type) {
        String attribute = CaptchaEnum.typeToAttribute(type);
        if (attribute == null) {
            throw new ServiceException("验证码类型不合法");
        }
        if (width == null) {
            width = CAPTCHA_WIDTH;
        }
        if (height == null) {
            height = CAPTCHA_HEIGHT;
        }

        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(width, height, CAPTCHA_COUNT, CAPTCHA_LINE);
        if (log.isDebugEnabled()) {
            log.info("验证码为 {}", captcha.getCode());
        }

        ServletRequestAttributes servletRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes());
        servletRequest.getRequest().getSession().setAttribute(attribute, captcha.getCode());

        try {
            HttpServletResponse response = servletRequest.getResponse();
            if (response != null) {
                captcha.write(response.getOutputStream());
            }
        } catch (IOException e) {
            log.error("输出验证码异常：" + e.getMessage(), e);
        }
    }

    @Override
    public Boolean isLoginCaptchaRequired() {
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
                .getRequest().getSession();
        return session.getAttribute(SecurityConfig.FAILED_LOGIN) != null;
    }

}
